package com.dqp.cslggroup.JWXT;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewStub;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import androidx.appcompat.widget.Toolbar;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.dqp.cslggroup.Api.jwxtApi;
import com.dqp.cslggroup.Api.xxmhApi;
import com.dqp.cslggroup.EventBus.MessageEvent;
import com.dqp.cslggroup.Features.Setting;
import com.dqp.cslggroup.R;
import com.dqp.cslggroup.UI.AlertDialog;
import com.dqp.cslggroup.UI.BaseActivity;
import com.dqp.cslggroup.UI.KjAdapter;
import com.dqp.cslggroup.Util.*;
import com.dqp.cslggroup.bean.Kj;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jsoup.Connection;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SearchKj extends BaseActivity {
    private String use_url;
    private Map<String, String> cookies = null;
    private String stuNum;
    private String xmmc, xnmc, xqmmc, xmcj;
    private Connection.Response response;
    private ListView listView;
    private LinearLayout item_cx;
    private ViewStub viewstub_loading;
    private ViewStub viewstub_null;
    ExecutorService threadPool = Executors.newFixedThreadPool(2);

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.inquire_kj);
        EventBus.getDefault().register(this);
        Toolbar toolbar = findViewById(R.id.include_toolbar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
        listView = findViewById(R.id.kj_list);
        stuNum = SharedPreferencesUtil.getStringSp(this, "stuNum", null);
        initCmp();
        getCookies();
        kj();
    }

    public void getCookies() {
//        List list = MyApplication.getDaoInstant().getStudentDao().queryBuilder().where(studentDao.Properties.Xh.eq(stuNum)).build().list();
//        if (list.size() > 0) return;
        Map<String, String> map = SharedPreferencesUtil.getMap(this, "cookies");
        long time = SharedPreferencesUtil.getLongSp(this, "cookiesTime", 0);
        long nowTime = GetTimeUtil.getCurrentTimeMillis();
        long x = GetTimeUtil.minuteDifference(nowTime, time);
        if (x < 10) {
            cookies = map;
        } else {
            String xxmh = SharedPreferencesUtil.getStringSp(this, "password_XXMH", null);
            String sno = SharedPreferencesUtil.getStringSp(this, "stuNum", null);
            String jwxt = SharedPreferencesUtil.getStringSp(this, "password_JWXT", null);
            if (!StringUtil.isEmpty(xxmh, sno, jwxt)) {
                viewstub_loading.setVisibility(View.VISIBLE);
                threadPool.execute(() -> {
                    JSONObject jsonObject = xxmhApi.login(sno, xxmh, "0");
                    if (Result.jsonResultIsTure(jsonObject)) {
                        JSONObject object = jsonObject.getJSONObject("info");
                        Map<String, String> xxmhCookies = JSONObject.parseObject(object.toJSONString(), new TypeReference<Map<String, String>>() {
                        });
                        if (xxmhCookies == null || xxmhCookies.size() < 2) return;
                        object = jwxtApi.login(xxmhCookies, sno, jwxt, "0");
                        if (Result.jsonResultIsTure(object)) {
                            cookies = xxmhCookies;
                            CookiesUtil.save(this, cookies);
                            EventBus.getDefault().post(new MessageEvent("JWXT_main", 12, null));
                        }
                    } else if (jsonObject.containsKey("resultMsg") && jsonObject.getJSONObject("resultMsg").containsKey("密码错误")) {
                        alertDialog("密码错误", "您绑定的信息门户账号密码错误，您近期是否进行了密码更改？" +
                                "现已无法正常使用该模块功能，为确保正常使用请前往设置重新绑定！");
                    }
                });
            } else {
                alertDialog("账号未绑定", "检测到您绑定的信息门户、教务系统账号或密码信息缺失，无法正常使用该模块功能，" +
                        "为确保正常使用请前往设置进行绑定！");
            }
        }
    }

    public void alertDialog(String title, String msg) {
        AlertDialog alertDialog = new AlertDialog(this);
        alertDialog.builder();
        alertDialog.setGone()
                .setTitle(title)
                .setMsg(msg)
                .setMsgGravity(false)
                .setNegativeButton("设置", R.color.colorAccent, v1 -> {
                    alertDialog.dismiss();
                    UiUtils.startActivity(this, Setting.class);
                })
                .setPositiveButton("取消", R.color.colorAccent, v2 -> {
                    alertDialog.dismiss();
                    finish();
                })
                .show();
    }


    @SuppressLint("HandlerLeak")
    private void initCmp() {
        TextView ksmc, kssj, cdmc, kcmc;
        ksmc = findViewById(R.id.text_xf);
        kssj = findViewById(R.id.text_cj);
        cdmc = findViewById(R.id.text_jd);
        kcmc = findViewById(R.id.text_kc);
        item_cx = findViewById(R.id.item_cx);
        kcmc.setText("项目名称");
        ksmc.setText("报名学年");
        cdmc.setText("项目成绩");
        kssj.setText("报名学期");
        viewstub_loading = findViewById(R.id.viewstub_loading);
        viewstub_null = findViewById(R.id.viewstub_null_date);
    }


    public void kj() {
        EventBus.getDefault().post(new MessageEvent("SearchKj", 1, null));
        new Thread(() -> {
            JSONObject jsonObject = jwxtApi.getGradeTest(stuNum, cookies);
            if (!jsonObject.containsKey("detial")) EventBus.getDefault().post(new MessageEvent("SearchKj", 7, null));
            jsonObject = jsonObject.getJSONObject("detial");
            if (!jsonObject.containsKey("exam")) EventBus.getDefault().post(new MessageEvent("SearchKj", 7, null));
            JSONArray kjbm = JSON.parseArray(jsonObject.getString("exam"));
            List<Kj> kjList = new ArrayList<>();
            for (Object o : kjbm) {
                JSONObject kj = (JSONObject) o;
                Kj kjs = new Kj();
                xmmc = kj.getString("xmmc");
                xnmc = kj.getString("xnmc");
                xqmmc = kj.getString("xqmmc");
                xmcj = kj.getString("xmcj");
                kjs.setXmcj(xmcj);
                kjs.setXmmc(xmmc);
                kjs.setXnmc(xnmc);
                kjs.setXqmmc(xqmmc);
                kjList.add(kjs);
            }
            EventBus.getDefault().post(new MessageEvent("SearchKj", 3, kjList));
        }).start();

    }

    private void initList(List<Kj> kjList) {
        if (kjList.size() > 0) {
            KjAdapter kjAdapter = new KjAdapter(kjList, this);
            listView.setAdapter(kjAdapter);
            EventBus.getDefault().post(new MessageEvent("SearchKj", 2, null));
        } else {
            EventBus.getDefault().post(new MessageEvent("SearchKj", 6, null));
        }
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event.getEvent().equals("SearchKj")) {
            switch (event.getWhat()) {
                case 1:
                    viewstub_loading.setVisibility(View.VISIBLE);
                    break;
                case 2:
                    viewstub_loading.setVisibility(View.GONE);
                    break;
                case 3:
                    initList((List<Kj>) event.getObj());
                    break;
                case 4:
                    viewstub_loading.setVisibility(View.GONE);
                    ToastUtil.showToast("🤦‍网络异常");

                    break;
                case 5:
                    viewstub_loading.setVisibility(View.GONE);
                    ToastUtil.showToast("🤦数据异常");
                    break;
                case 7:
                    viewstub_loading.setVisibility(View.GONE);
                    ToastUtil.showToast("🤦数据跑丢了！");
                    break;
                case 6:
                    viewstub_loading.setVisibility(View.GONE);
                    item_cx.setVisibility(View.GONE);
                    viewstub_null.setVisibility(View.VISIBLE);
                    break;
            }
        }
    }

}